﻿(function() {
    'use strict';

    angular.module('app.controllers', [])
        .controller('MainController', MainController)
        .controller('MonitorController', MonitorController)
        .controller('PingController', PingController)
        .controller('TelnetController', TelnetController)
        .controller('MonitorModalController', MonitorModalController)
        .controller('ServerModalController', ServerModalController);
    
    /** @ngInject */
    function MainController($rootScope, $scope, $interval, $utils, $const, msgHubService) {
        var vm = this;
        vm.serverList = [];
        $scope.loadButtonCss = function (num) {
            return num && num > 1000 ? 'btn-danger' : 'btn-default';
        };
        $scope.loadProgressCss = function (loadValue) {
            return loadValue && loadValue > 90 ? 'progress-bar-danger' : '';
        };
        
        msgHubService.init(vm);  //将ViewModel传入msgHubService，以便msgHub接收消息后更新vm
        msgHubService.receiveHeartbeat = function (r) {
            updateViewData(r.hostId, function (idx, server) {
                server.heartBeatUpdated = new Date();
                server.heartBeatText = r.isAlive ? 'Up' : 'Down';
                server.heartBeatCss = r.isAlive ? 'glyphicon-play' : 'glyphicon-info-sign';
            });
        };
        msgHubService.receiveCPU = function (r) {
            updateViewData(r.hostId, function (idx, server) {
                server.cpuProcessorCount = r.processorCount;
                if (server.cpuLoadList.length >= 12)
                    server.cpuLoadList.splice(11, server.cpuLoadList.length - 11); //最多显示12条（移除末条）                    

                var loadPrgCss = $scope.loadProgressCss(r.cpuLoad);
                server.cpuLoadList.unshift({ 'date': new Date(), 'num': r.cpuLoad, 'css': loadPrgCss });  //入栈
            });
        };
        msgHubService.receiveDisk = function (r) {
            updateViewData(r.hostId, function (idx, server) {
                server.diskList = r.items;
            });
        };
        msgHubService.receiveMemory = function (r) {
            updateViewData(r.hostId, function (idx, server) {
                if (server.memoryLoadList.length >= 12)
                    server.memoryLoadList.splice(11, server.cpuLoadList.length - 11); //最多显示12条（移除末条） 

                var loadPrgCss = $scope.loadProgressCss(r.memoryLoad);
                server.memoryPhysical = r.physical;
                server.memoryLoadList.unshift({ 'date': new Date(), 'num': r.memoryLoad, 'css': loadPrgCss });  //入栈
            });
        };
        msgHubService.receiveCurrentConnection = function (r) {
            updateViewData(r.hostId, function (idx, server) {
                server.connectionList = r.items;
            });
        };
        
        //AJAX加载server列表
        $utils.get($rootScope.wwwUrl + '/data/server.json', null, function (res) {
            vm.serverList = res.data.all;
            if (vm.serverList && vm.serverList.length > 0) {
                for (var i = 0; i < vm.serverList.length; i++) {
                    vm.serverList[i].heartBeatText = 'Standby';
                    vm.serverList[i].heartBeatCss = 'glyphicon-time';
                    vm.serverList[i].heartBeatUpdated = null;
                    vm.serverList[i].cpuProcessorCount = 0;
                    vm.serverList[i].cpuLoadList = [{ 'date': new Date(), 'num': 0, 'css': '' }];
                    vm.serverList[i].memoryPhysical = null;
                    vm.serverList[i].memoryLoadList = [{ 'date': new Date(), 'num': 0, 'css': '' }];
                    vm.serverList[i].diskList = [];
                    vm.serverList[i].connectionList = [];
                    vm.serverList[i].tableVisible = false;
                }
            } else {
                vm.nothingMessage = "No data is loaded, please confirm that the configuration is correct.";
            }
        });
        
        var updateViewData = function (hostId, callback) {
            for (var i = 0; i < vm.serverList.length; i++) {
                if (vm.serverList[i].id.toLowerCase() == hostId.toLowerCase()) {
                    if (callback != null) callback(i, vm.serverList[i]);
                    break;
                }
            }
        };

        //写个interval操作，页面会自动随 model 动态刷新，连 $scope.$apply(..) 都不需要
        $interval(function () {
            /*console.log('refresh ui');*/
            var dtNow = new Date();
            for (var i = 0; i < vm.serverList.length; i++) {
                var temp = vm.serverList[i].heartBeatUpdated;
                if (temp && temp < new Date(dtNow.getTime() - 1000 * 10)) { //超过10秒没有收到心跳数据
                    vm.serverList[i].heartBeatText = 'Down';
                    vm.serverList[i].heartBeatCss = 'glyphicon-info-sign';
                }
            }
        }, 500);
        
        //弹出CPU统计报告
        $scope.showCpuReport = function ($index) {
            var viewData = vm.serverList[$index].cpuLoadList;
            $utils.showModal('serverModal', 'ServerModalController', viewData, function () {
                //窗体关闭回调
            });
        };
        //弹出内存统计报告
        $scope.showMemoryReport = function ($index) {
            var viewData = vm.serverList[$index].memoryLoadList;
            $utils.showModal('serverModal', 'ServerModalController', viewData, function () {
                //窗体关闭回调
            });
        };
        //展开/关闭Server详情
        $scope.toggleDetails = function ($index) {
            var tableVisible = vm.serverList[$index].tableVisible;
            vm.serverList[$index].tableVisible = !tableVisible;
        };
    }

    /** @ngInject */
    function MonitorController($rootScope, $scope, $interval, $utils, $const, msgHubService) {
        var vm = this;
        vm.monitorList = [];
        msgHubService.init(vm);  //将ViewModel传入msgHubService，以便msgHub接收消息后更新vm
        msgHubService.receiveMonitor = function (r) {
            updateViewData(r.id, function (idx, monitor) {
                monitor.statusCss = r.isOk ? 'glyphicon-play' : 'glyphicon-info-sign';
                if (monitor.statusTextList.length >= 10)
                    monitor.statusTextList.splice(9, monitor.statusTextList.length - 9); //最多显示10条（移除末条）
                
                var statusTextCss = r.isOk ? 'text-success' : 'text-danger';
                monitor.statusTextList.unshift({ 'date': new Date(), 'text': r.text, 'css': statusTextCss }); //入栈
                //console.log(monitor.statusTextList);
            });
        };

        //AJAX加载monitor列表
        $utils.get($rootScope.wwwUrl + '/data/monitor.json', null, function (res) {
            vm.monitorList = res.data.all;
            if (vm.monitorList && vm.monitorList.length > 0) {
                vm.hasNothing = false;
                for (var i = 0; i < vm.monitorList.length; i++) {
                    vm.monitorList[i].statusCss = 'glyphicon-time';
                    vm.monitorList[i].statusTextList = [{ 'date': new Date(), 'text': 'Standby', 'css': '' }];
                    //console.log(monitor.statusTextList);
                }
            } else {
                vm.nothingMessage = "No data is loaded, please confirm that the configuration is correct.";
            }
        });
        
        var updateViewData = function (monitorId, callback) {
            for (var i = 0; i < vm.monitorList.length; i++) {
                if (vm.monitorList[i].id.toLowerCase() == monitorId.toLowerCase()) {
                    if (callback != null) callback(i, vm.monitorList[i]);
                    break;
                }
            }
        };

        //写个interval操作，页面会自动随 model 动态刷新，连 $scope.$apply(..) 都不需要
        $interval(function () {
            /*console.log('refresh ui');*/
            var dtNow = new Date();
            for (var i = 0; i < vm.monitorList.length; i++) {
                var temp = vm.monitorList[i].statusTextList[0].date;
                if (temp && temp < new Date(dtNow.getTime() - 1000 * 30)) { //超过30秒没有收到数据
                    vm.monitorList[i].statusCss = 'glyphicon-info-sign';                    
                    vm.monitorList[i].statusTextList.unshift({ 'date': new Date(), 'text': 'No response [FAIL]', 'css': 'text-danger' });
                }
            }
        }, 500);

        //弹出统计报告
        $scope.showReport = function ($index) {
            var viewData = vm.monitorList[$index].statusTextList;
            $utils.showModal('monitorModal', 'MonitorModalController', viewData, function (arg) {
                //窗体关闭回调
            });
        };
    }

    /** @ngInject */
    function PingController($rootScope, $scope, $stateParams, msgHubService) {
        var vm = this;
        vm.messageList = [];
        vm.dest = $stateParams.ip;        
        msgHubService.init(vm);  //将ViewModel传入msgHubService，以便msgHub接收消息后更新vm
        msgHubService.receiveMessage = function (msg) {            
            $scope.$apply(function () {
                vm.messageList.push(msg);
            });
        };
        $scope.submitPing = function () {
            if (vm.dest && vm.dest.length > 0) {                
                vm.messageList = ['Sending data to the server...'];
                msgHubService.sendPingOutput(vm.dest);
            }
        };
    }

    /** @ngInject */
    function TelnetController($rootScope, $scope, msgHubService) {
        var vm = this;
        vm.messageList = [];
        msgHubService.init(vm);  //将ViewModel传入msgHubService，以便msgHub接收消息后更新vm
        msgHubService.receiveMessage = function (msg) {            
            $scope.$apply(function () {
                vm.messageList.push(msg);
            });
        };
        $scope.submitTelnet = function () {
            if (vm.host && vm.port) {
                vm.messageList = ['Sending data to the server...'];
                msgHubService.sendTelnetOutput(vm.host, vm.port);
            }
        };
    }

    /** @ngInject */
    function MonitorModalController($scope, $uibModalInstance, $utils, $input) {
        var vm = this;
        vm.statusTextList = [];
        if ($input.viewData) {
            $input.viewData.forEach(function (ele, i, arr) {
                vm.statusTextList.push({
                    'time': $utils.getTimeString(ele.date),
                    'css': ele.css,
                    'text': ele.text
                });
            });
        }
        $scope.dismissModal = function () {  //关闭模态窗口
            $uibModalInstance.close('finish');  //传递一个对象
        };
    }

    /** @ngInject */
    function ServerModalController($scope, $uibModalInstance, $utils, $input) {
        var vm = this;
        vm.loadValueList = [];
        if ($input.viewData) {
            $input.viewData.forEach(function (ele, i, arr) {
                vm.loadValueList.push({
                    'time': $utils.getTimeString(ele.date),
                    'num': ele.num,
                    'css': ele.css
                });
            });
        }
        $scope.dismissModal = function () {  //关闭模态窗口
            $uibModalInstance.close('finish');  //传递一个对象
        };
    }
    
})();


//https://www.nuget.org/packages/AngularJs.SignalR.Hub/
//https://github.com/JustMaier/angular-signalr-hub